package Async2Sync;

import java.util.concurrent.*;
import java.util.function.Supplier;

/**
 * 异步转同步示例代码<br/>
 *
 */
public class Async2SyncDemo {

    private static final ExecutorService POOL = Executors.newCachedThreadPool();

    /**
     * 异步转同步工具类<br/>
     *
     * @param asyncTask
     * @param timeout
     * @param unit
     * @return
     * @param <T>
     * @throws Exception
     */
    public static <T> T sync(Supplier<T> asyncTask, long timeout, TimeUnit unit) throws Exception {
        // 异步调用
        Future<T> future = POOL.submit(asyncTask::get);
        try {
            // 阻塞直到完成or超时
            return future.get(timeout, unit);
        } catch (TimeoutException e) {
            // 调用future.cancle 释放资源
            future.cancel(true);
            throw new RuntimeException("任务超时", e);
        }
    }

    public static void main(String[] args) throws  Exception {
        String result = sync(
                () -> {
                    try {
                        Thread.sleep(5000L);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    return "hello async -> sync";
                }, 30, TimeUnit.SECONDS
        );
        System.out.println(" result:" + result);
        POOL.shutdown();
    }
}
